package cn.ibobo.lease.admin.controller;

import cn.ibobo.lease.admin.annotation.ApplicationParam;
import cn.ibobo.lease.common.enums.ResultEnum;
import cn.ibobo.lease.common.util.ResultVOUtil;
import cn.ibobo.lease.common.util.UploadUtil;
import cn.ibobo.lease.common.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.List;

@RestController
@Api(tags = "图片上传接口")
@RequestMapping("uploadImgs")
public class UploadImgController {
	
	@Autowired
    private ResultVOUtil<Object> resultVOUtilObj;
    @Autowired
    private ApplicationParam param;
    
    private static final Log LOGGER = LogFactory.getLog(UploadImgController.class);

	/**
	 * @Description 图片单个上传
	 * @Author lililiang
	 * @Date 2018/12/11 19:36
	 * @Param [base64Img, file, path]
	 * @Return cn.ibobo.lease.common.vo.ResultVO<java.lang.Object>
	 */
    @ApiOperation("PC-APP-单个文件上传")
    @PostMapping("upload")
    public ResultVO<Object> upload(
    		@ApiParam(value = "base64图片（是base64图片，必传，图片文件不必传）") @RequestParam(value = "base64Img", required = false) String base64Img,
    		@ApiParam(value = "图片") @RequestParam(required = false) MultipartFile file,
            @ApiParam(value = "保存路径,使用模块名/功能名/的形式，例如shop模块的头像功能为SHOP/icon", defaultValue = "admin/other") @RequestParam(required = true, defaultValue = "admin/other") String path) {
        try {
        	if (base64Img != null) {
                BASE64Decoder decoder = new BASE64Decoder();
                // 解密
                byte[] b = decoder.decodeBuffer(base64Img.substring(base64Img.indexOf(",") + 1));
                // 处理数据
                for (int i = 0; i < b.length; ++i) {
                    if (b[i] < 0) {
                        b[i] += 256;
                    }
                }
                InputStream is = new ByteArrayInputStream(b);
                BufferedImage image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_BGR);
                File f = new File(param.getUploadPath() + "test.jpg");
                if (!f.exists()) {
                    f.mkdirs();
                }
                ImageIO.write(image, "jpg", f);
                OutputStream out = new FileOutputStream(f);
                out.write(b);
                out.flush();
                out.close();
                String s = UploadUtil.upLoadFile(UploadUtil.fileToMultipartFile(f), param.getUploadPath(), path);
                if (s != null){
                    return resultVOUtilObj.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), param.getWebPath() + s);
                }else{
                    return resultVOUtilObj.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
                }
        	}
            if (null != file) {
                String s = UploadUtil.upLoadFile(file, param.getUploadPath(), path);
                if (s != null){
                    return resultVOUtilObj.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), param.getWebPath() + s);
                }else{
                    return resultVOUtilObj.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
                }
            }
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
            LOGGER.error("\n--upLoadFile()--上传图片失败! ");
            e.printStackTrace();
        }
        return resultVOUtilObj.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
    }


    /**
     * @Description 图片批量上传
     * @Author lililiang
     * @Date 2018/12/11 19:36
     * @Param [file, path]
     * @Return cn.ibobo.lease.common.vo.ResultVO<java.lang.Object>
     */
    @ApiOperation("PC-APP-图片批量上传")
    @PostMapping("uploadImg")
    public ResultVO<Object> uploadImg(
            @ApiParam(value = "图片") @RequestParam(required = true) MultipartFile[] file,
            @ApiParam(value = "保存路径,使用模块名/功能名/的形式，admin/other" ,defaultValue = "life/other") @RequestParam(required = true ,defaultValue = "admin/other") String path) {
        try {
            if (null != file) {
                List<String> imgPaths = UploadUtil.upLoadFiles(file, param.getUploadPath(), path, param.getWebPath());
                if (imgPaths != null){
                    return resultVOUtilObj.success(ResultEnum.SUCCESS.getCode(), ResultEnum.SUCCESS.getMsg(), imgPaths);
                }else{
                    return resultVOUtilObj.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
                }
            }
        } catch (IOException e) {
            LOGGER.info("\n--uploadImg()--上传图片失败, 服务异常! ");
        }
        return resultVOUtilObj.error(ResultEnum.FAIL.getCode(), ResultEnum.FAIL.getMsg());
    }
}


